package com.je.thrid.thread;

import com.google.common.collect.Lists;
import com.je.core.service.MetaService;
import com.je.core.service.MetaServiceImpl;
import com.je.core.util.SpringContextHolder;
import com.je.core.util.bean.DynaBean;
import com.je.thrid.vo.ParseVo;
import com.je.thrid.vo.ThridAddThreadVo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ThridAddTread extends Thread {
    /**
     * 三方添加vo
     */
    private ThridAddThreadVo thridAddThreadVo;

    private ThridAddTread() {}

    public ThridAddTread(ThridAddThreadVo thridAddThreadVo) {
        this.thridAddThreadVo = thridAddThreadVo;
    }

    @Override
    public void run() {
        try {
            if (thridAddThreadVo == null) {
                return;
            }
            MetaService metaService = SpringContextHolder.getBean(MetaServiceImpl.class);
            List<DynaBean> convertedBeans = Lists.newArrayList();
            List<DynaBean> readedList = new ArrayList<>();
            try {
                readedList =
                    (List<DynaBean>)thridAddThreadVo.getAbstractDynaBeanImportService().getImportSource().read();
            } catch (Exception e) {
                throw new RuntimeException("read方法返回错误，请检查！");
            }
            List<DynaBean> sortedList = thridAddThreadVo.getAbstractDynaBeanImportService().doSort(readedList);
                sortedList.forEach(eachReadBean -> {
                    ParseVo parseVo =
                            thridAddThreadVo.getAbstractDynaBeanImportService().getImportParser().parse(eachReadBean,thridAddThreadVo.getAbstractDynaBeanImportService().getCustomParameters());
                    convertedBeans.add(parseVo.getDynaBean());
                    if (parseVo.isInsert()) {
                        metaService.insert(eachReadBean);
                    }
            });
            thridAddThreadVo.getAbstractDynaBeanImportService().customMethod(sortedList,
                thridAddThreadVo.getAbstractDynaBeanImportService().getCustomParameters());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
